package com.gui.pay.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.gui.entity.R;
import com.gui.pay.service.WxPayService;
import com.gui.registration.model.RegistrationRecord;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 言叶
 * Date：2025/9/5
 */
@RestController
@RequestMapping("/wxPay")
@CrossOrigin
@AllArgsConstructor
public class WxPayController {
    private final WxPayService wxPayService;
    /*
    * 微信支付统一下单接口
    * 商品描述，商户订单号。标价金额
     */
    @GetMapping("/unifiedOrder")
    public R unifiedOrder(String body, String outTradeNo,@RequestParam(value = "totalFee") Long totalFee) {
        Map<String, String> resultMap = wxPayService.unifiedOrder(body, outTradeNo, totalFee);
        return R.success(resultMap);
    }

    //接受微信支付异步通知
    @PostMapping("notifyurl")
    public String notifyurl(HttpServletRequest request){

        System.out.println("进来了!!");
        InputStream inStream;
        try {
            //读取支付回调数据
            inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            // 将支付回调数据转换成xml字符串
            String result = outSteam.toString("utf-8");
            //将xml字符串转换成Map结构 Map<String, String> map = WXPayUtil.xmlToMap(result)
            Map<String, String> map = WXPayUtil.xmlToMap(result);
            // 获取回调数据
            // 判断是否回调成功
            String returnCode =  map.get("return_code");

            if("SUCCESS".equalsIgnoreCase(returnCode)){
                RegistrationRecord record = new RegistrationRecord();
                String orderId = map.get("out_trade_no");
                record.setOrderId(orderId);
                record.setPayType(2L);
                record.setIsPay(1L);
                record.setTransactionId(map.get("transaction_id"));
                // 说明回调成功 每次张订单只处理一次  分布式锁  redis
                // key:
                // transaction_id 微信那边的订单号 查询微信订单的时候非常快
                // 把支付公司的订单号保存到数据库(挂号信息表)

                // 获取支付状态
                String resultCode = map.get("result_code");
                if("SUCCESS".equalsIgnoreCase(resultCode)){
                    // 说真的成功  交易成功
                    wxPayService.updateOrderStatus(record);
                }
            }

            System.out.println(result);

            //响应数据设置
            Map respMap = new HashMap();
            respMap.put("return_code","SUCCESS");
            respMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
            //记录错误日志
        }
        return null;
    }

}
